package com.hmdp.utils;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

//Redis分布式锁
public class SimpleRedisLock implements ILOCK {

    private String name;
    private static final String KEY_PREFIX="lock:";

    private StringRedisTemplate stringRedisTemplate;

    private static final String ID_PREFIX= UUID.randomUUID().toString()+"-";

    //配置引入Lua
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    //类的有参构造函数
    //要创建Reids分布式锁，必须先创建有参对象，才能使用分布式锁
    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }




    //尝试获取分布式锁
    @Override
    public boolean trylock(long timeoutSec) {
        //获取线程标识
        String ThteadId = ID_PREFIX+Thread.currentThread().getId();

        //参数：锁的key，锁的Value，锁的时间，锁时间的类型
        //返回的参数会转型为Boolean
        Boolean RedisLock = stringRedisTemplate.opsForValue().
                setIfAbsent(KEY_PREFIX + name, ThteadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(RedisLock);//防止获取锁时返回空值，结果直接返回空。与TRUE判断，如果不相同统一返回FALSE
    }


    //释放锁
    @Override
    public void unlock() {
        //调用Lua脚本 确保判断锁与释放锁是原子性的
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX+name),
                ID_PREFIX+Thread.currentThread().getId()
        );

    }

//    //释放锁
//    @Override
//    public void unlock() {
//        //获取线程标识
//        String ThteadId = ID_PREFIX+Thread.currentThread().getId();
//        //获取Redis内的标识
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//        //判断是否相同
//        if (ThteadId.equals(id)){
//            stringRedisTemplate.delete(KEY_PREFIX+name);
//        }
//    }
}
